package com.luochen.cdpt.util;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {
    /**
     * copy不为null的属性值
     *
     * @param target    目标对象
     * @param source    源对象
     * @param <T>
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     */
    public static <T> void copyPropertiesNotNull(T target, T source) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        copyPropertiesNotNull(target, source, new String[]{});
    }

    /**
     *
     * @param target    目标对象
     * @param source    源对象
     * @param ignores   需要忽略的字段
     * @param <T>
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     */
    public static <T> void copyPropertiesNotNull(T target, T source, String... ignores) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        List<String> ignoreList = Arrays.asList(ignores);
        //遍历target，获取字段
        Field[] targetFields = FieldUtils.getAllFields(target.getClass());
        //将source字段不为null值赋给target
        for (Field targetField : targetFields) {
            String fieldName = targetField.getName();
            if (CollectionUtils.contains(ignoreList.iterator(), fieldName)) {
                continue;
            }
            targetField.setAccessible(true);
            Object property = PropertyUtils.getProperty(source, fieldName);
            if (property == null) {
                continue;
            }
            PropertyUtils.setProperty(target, fieldName, property);
        }
    }
}
